<template>
	<view>
		<view class="">
			<view class="">日新增用户</view>
		</view>
		<echarts :option="option" style="height: 300px;" @click="echartsClick"></echarts>
	</view>
</template>

<script>
var _self;
const db = uniCloud.database();

export default {
	data() {
		return {
			option: {},
			startdate: new Date(new Date().getTime() - 1000*60*60*24*7), // 默认开始时间是7天前
			enddate: new Date()
		};
	},
	onLoad() {
		_self = this;
		this.cloudData2localData();
	},
	methods: {
		cloudData2localData() {
			db.collection('uni-id-users')
				.where("register_date>=" + _self.startdate.getTime() + " && register_date<=" + _self.enddate.getTime())
				.groupBy('dateToString(add(new Date(0),register_date),"%Y-%m-%d","+0800") as date')
				.groupField('count(*) as count')
				.get()
				.then((res) => {
					const resdata = res.result.data
					console.log("resdata: ", resdata);
					if (resdata) {
						// 转换resdata的keyvalue方式为以日期为key的新json格式，方便后面用key的方式直接取数
						var newdata = {};
						resdata.forEach(function(v, i) {
							// 数据库的日期格式本地转换下，不然后面用key取不到
							newdata[new Date(v.date).toLocaleDateString()] = v;
						});
						console.log("newdata: ", newdata);
						// 循环日期从startdate到enddate，构造uchart组件需要的数据
						var idate = _self.startdate
						let tempLineA = {
							notMerge: true, // 自定义变量：true代表不合并数据，比如从折线图变为柱形图则需设置为true；false或不写代表合并
							xAxis: {
								type: 'category',
								data: []
							},
							yAxis: {
								type: 'value'
							},
							series: [
								{
									data: [],
									type: 'line', // line折线图、bar柱状图
									showBackground: true,
									backgroundStyle: {
										color: 'rgba(220, 220, 220, 0.8)'
									}
								}
							]
						};
						while (idate <= _self.enddate) {
							tempLineA.xAxis.data.push(idate.toLocaleDateString())
							var newcount = 0
							// console.log(idate.toLocaleDateString());
							if (newdata[idate.toLocaleDateString()]) {
								// console.log("来过");
								newcount = newdata[idate.toLocaleDateString()].count
							}
							tempLineA.series[0].data.push(newcount)
							idate = idate.setDate(idate.getDate() + 1);
							idate = new Date(idate)
						}
						console.log("图表所需数据: ", tempLineA);
						this.option = tempLineA
					}
				}).catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					})
					console.log(err.message);
				}).finally(() => {
					// uni.hideLoading()
				})
		
		},
		/**
		 * 点击事件
		 * @param {Object} params
		 */
		echartsClick(params) {
			console.log('点击数据', params)
		}
	}
};
</script>

<style></style>
